'use strict';

const Controller = require('egg').Controller;

class GroupController extends Controller {
  async create() {
    const currentuserid = this.ctx.authUser.id;
    this.ctx.validate({
      ids: {
        type: "array", required: true, desc: "昵称"
      },

    });
    let ids = this.ctx.request.body.ids;
    let friends = await this.app.model.Friend.findAll({
      where: {
        user_id: currentuserid,
        friend_id: ids

      },
      include: [{
        model: this.app.model.User,
        as: "friendInfo",
        attributes: ['nickname', 'username']
      }]
    })
    if (!friends.length) {
      return this.ctx.apiFail("请选择自己的好友")
    }

    console.log(friends, "friends")
    let name = friends.map(item => item.nickname || item.friendInfo.username)

    name.push(this.ctx.authUser.nickname || this.ctx.authUser.username)


    let res = await this.app.model.Group.create({
      name: name.join(","),
      avatar: "",
      user_id: currentuserid
    })

    let datas = friends.map(item => {
      return {
        user_id: item.friend_id,
        group_id: res.id
      }
    })
    datas.unshift({
      user_id: currentuserid,
      group_id: res.id

    })
    console.log(datas, "datas")
    let ress = await this.app.model.GroupUser.bulkCreate(datas);
    //消息推送
    let message = {
      id: (new Date()).getTime(), // 唯一id，后端生成唯一id
      from_avatar: this.ctx.authUser.avatar,// 发送者头像
      from_name: this.ctx.authUser.nickname || this.ctx.authUser.username, // 发送者昵称
      from_id: currentuserid, // 发送者id
      to_id: res.id, // 接收人/群 id
      to_name: res.name, // 接收人/群 名称
      to_avatar: res.avatar, // 接收人/群 头像
      chat_type: 'group', // 接收类型
      type: "system",// 消息类型
      data: "创建群聊成功，可以开始聊天了", // 消息内容
      options: {}, // 其他参数
      create_time: (new Date()).getTime(), // 创建时间
      isremove: 0, // 是否撤回
      group: res
    }
    datas.forEach(el => {
      let socket = null;
      if (this.app.ws.user) {
        socket = this.app.ws.user[el.user_id];

      }
      //验证对方是否在线

      if (!socket) {
        console.log(123333, "343331")
        this.service.cache.setList("getmessage_" + el.user_id, message)

      } else {
        console.log(123333, "34333")
        //消息推送
        socket.send(JSON.stringify({
          msg: "ok",
          data: message
        }))
        //存到历史记录
        this.service.cache.setList(`chatlog_${el.user_id}_user_${currentuserid}`, message);


      }
      //存储到自己的聊天记录
      this.service.cache.setList(`chatlog_${currentuserid}_user_${el.user_id}`, message);
    })
    this.ctx.apiSuccess(ress)
  }
  //群聊列表
  async list() {
    let currentuserId = this.ctx.authUser.id;
    let list = await this.app.model.Group.findAll({
      where: {
        status: 1
      },
      include: [{
        model: this.app.model.GroupUser,
        where: {
          user_id: currentuserId
        }
      }]
    })

    this.ctx.apiSuccess(list, "200")
  }
  //详情
  async info() {
    let currentuserId = this.ctx.authUser.id;

    this.ctx.validate({
      id: {
        type: "int", required: true, desc: "id"
      },

    });
    let id = this.ctx.request.body.id;
    let res = await this.app.model.Group.findOne({
      where: {
        status: 1,
        id
      },
      include: [{
        model: this.app.model.GroupUser,
        attributes: ['user_id', 'nickname'],
        include: [{
          model: this.app.model.User,
          attributes: ['id', 'nickname', 'avatar', 'username'],
        }]
      }]
    })
    if (!res) {
      return this.ctx.apiFail("该群聊不存在或已被禁用")
    }
    let index = res.group_users.findIndex(item => item.user_id == currentuserId);
    if (index == -1) {
      return this.ctx.apiFail("你不是该群里的成员")

    }
    this.ctx.apiSuccess(res)
  }
  //修改群名称
  async grouprename() {
    let currentid = this.ctx.authUser.id;
    let id = this.ctx.request.body.id;
    let name = this.ctx.request.name;
    this.ctx.validate({
      id: {
        type: "int", required: true, desc: "id"
      },
      name: {
        type: "string", required: true, desc: "name"
      },

    });
    let res = await this.app.model.Group.findOne({
      id: id,
      status: 1,
      include: [{
        model: this.app.model.GroupUser,
        attributes: ['user_id', 'nickname'],

      }]
    })
    if (!res) {
      return this.ctx.apiFail("群聊不存在或已删除")
    }
    let index = res.group_users.findIndex(item => item.user_id == currentid);
    if (index == -1) {
      return this.ctx.apiFail("你不是该群成员")
    }
    if (res.user_id !== currentid) {
      return this.ctx.apiFail("你不是群主")
    }
    res.name = this.ctx.request.body.name;
    res.save()
    let from_name = res.group_users[index].nickname || this.ctx.authUser.nickname || this.ctx.authUser.username;
    let message = {
      id: (new Date()).getTime(), // 唯一id，后端生成唯一id
      from_avatar: this.ctx.authUser.avatar,// 发送者头像
      from_name: from_name, // 发送者昵称
      from_id: currentid, // 发送者id
      to_id: res.id, // 接收人/群 id
      to_name: res.name, // 接收人/群 名称
      to_avatar: res.avatar, // 接收人/群 头像
      chat_type: 'group', // 接收类型
      type: "system",// 消息类型
      data: `${from_name}修改群名称为${res.name}`, // 消息内容
      options: {}, // 其他参数
      create_time: (new Date()).getTime(), // 创建时间
      isremove: 0, // 是否撤回
      group: res
    }
    res.group_users.forEach(el => {
      // if (el.user_id !== currentid) {
        //拿到对方的socket
        let socket = null;
        if (this.app.ws.user) {
          socket = this.app.ws.user[el.user_id];

        }
        //验证对方是否在线

        if (!socket) {
          console.log(123333, "343331")
          this.service.cache.setList("getmessage_" + el.user_id, message)

        } else {
          console.log(123333, "34333")
          //消息推送
          socket.send(JSON.stringify({
            msg: "ok",
            data: message
          }))
          //存到历史记录
          this.service.cache.setList(`chatlog_${el.user_id}_group_${currentid}`, message);
        }
      // }
    });
    this.ctx.apiSuccess(message)
    // this.ctx.apiSuccess(res)
  }
  //修改群公告
  async groupupdateremark() {
    let currentid = this.ctx.authUser.id;
    let id = this.ctx.request.body.id;
    let name = this.ctx.request.name;
    this.ctx.validate({
      id: {
        type: "int", required: true, desc: "id"
      },
      remark: {
        type: "string", required: true, desc: "remark"
      },

    });
    let res = await this.app.model.Group.findOne({
      id: id,
      status: 1,
      include: [{
        model: this.app.model.GroupUser,
        attributes: ['user_id', 'nickname'],

      }]
    })
    if (!res) {
      return this.ctx.apiFail("群聊不存在或已删除")
    }
    let index = res.group_users.findIndex(item => item.user_id == currentid);
    if (index == -1) {
      return this.ctx.apiFail("你不是该群成员")
    }
    if (res.user_id !== currentid) {
      return this.ctx.apiFail("你不是群主")
    }
    res.remark = this.ctx.request.body.remark;
    res.save()
    let from_name = res.group_users[index].nickname || this.ctx.authUser.nickname || this.ctx.authUser.username;
    let message = {
      id: (new Date()).getTime(), // 唯一id，后端生成唯一id
      from_avatar: this.ctx.authUser.avatar,// 发送者头像
      from_name: from_name, // 发送者昵称
      from_id: currentid, // 发送者id
      to_id: res.id, // 接收人/群 id
      to_name: res.name, // 接收人/群 名称
      to_avatar: res.avatar, // 接收人/群 头像
      chat_type: 'group', // 接收类型
      type: "system",// 消息类型
      data: `${from_name}修改群公告为${res.remark}`, // 消息内容
      options: {}, // 其他参数
      create_time: (new Date()).getTime(), // 创建时间
      isremove: 0, // 是否撤回
      group: res
    }
    res.group_users.forEach(el => {
      // if (el.user_id !== currentid) {
        //拿到对方的socket
        let socket = null;
        if (this.app.ws.user) {
          socket = this.app.ws.user[el.user_id];

        }
        //验证对方是否在线

        if (!socket) {
          console.log(123333, "343331")
          this.service.cache.setList("getmessage_" + el.user_id, message)

        } else {
          console.log(123333, "34333")
          //消息推送
          socket.send(JSON.stringify({
            msg: "ok",
            data: message
          }))
          //存到历史记录
          this.service.cache.setList(`chatlog_${el.user_id}_group_${currentid}`, message);
        }
      // }
    });
    this.ctx.apiSuccess(message)
    // this.ctx.apiSuccess(res)
  }
  //修改我在群里的昵称
  async groupupdatenickname() {
    let currentid = this.ctx.authUser.id;
    let id = this.ctx.request.body.id;
    let nickname = this.ctx.request.body.nickname;
    this.ctx.validate({
      id: {
        type: "int", required: true, desc: "id"
      },
      nickname: {
        type: "string", required: true, desc: "nickname"
      },

    });
    let res = await this.app.model.Group.findOne({
      id: id,
      status: 1,
      include: [{
        model: this.app.model.GroupUser,
        attributes: ['user_id', 'nickname'],

      }]
    })
    if (!res) {
      return this.ctx.apiFail("群聊不存在或已删除")
    }
    let index = res.group_users.findIndex(item => item.user_id == currentid);
    if (index == -1) {
      return this.ctx.apiFail("你不是该群成员")
    }
    // if (res.user_id !== currentid) {
    //   return this.ctx.apiFail("你不是群主")
    // }
    let ress = await this.app.model.GroupUser.findOne({
      where:{
        user_id: currentid,
        group_id: id,
     
      }
       })
    console.log(ress,"ress")
    
    if (ress) {
      await ress.update({
        nickname: nickname
      })
      // ress.nickname=nickname
      // ress.save()
      return this.ctx.apiSuccess("修改成功")
    }
  }
  async quit(){
    let currentid = this.ctx.authUser.id;
    let id = this.ctx.request.body.id;
    let nickname = this.ctx.request.body.nickname;
    this.ctx.validate({
      id: {
        type: "int", required: true, desc: "id"
      },
     
    });
    let res = await this.app.model.Group.findOne({
      id: id,
      status: 1,
      include: [{
        model: this.app.model.GroupUser,
        attributes: ['user_id', 'nickname'],

      }]
    })
    if (!res) {
      return this.ctx.apiFail("群聊不存在或已删除")
    }
    let index = res.group_users.findIndex(item => item.user_id == currentid);
    if (index == -1) {
      return this.ctx.apiFail("你不是该群成员")
    }
    let from_name = res.group_users[index].nickname || this.ctx.authUser.nickname || this.ctx.authUser.username;
    let message = {
      id: (new Date()).getTime(), // 唯一id，后端生成唯一id
      from_avatar: this.ctx.authUser.avatar,// 发送者头像
      from_name: from_name, // 发送者昵称
      from_id: currentid, // 发送者id
      to_id: res.id, // 接收人/群 id
      to_name: res.name, // 接收人/群 名称
      to_avatar: res.avatar, // 接收人/群 头像
      chat_type: 'group', // 接收类型
      type: "system",// 消息类型
      data: ``, // 消息内容
      options: {}, // 其他参数
      create_time: (new Date()).getTime(), // 创建时间
      isremove: 0, // 是否撤回
      group: res
    }
    if(res.user_id == currentid){
      await this.app.model.Group.destroy({
        where:{
          id:id
        }
      });
      this.ctx.apiSuccess("成功")
      message.data="该群已经解散"
    }else{
      await this.app.model.GroupUser.destroy({
        where:{
          group_id:id,
          user_id:currentid
        }
      });
      this.ctx.apiSuccess("成功")
           message.data=`${from_name}已退出群聊`
    }
    res.group_users.forEach(el => {
      if (el.user_id !== currentid) {
        //拿到对方的socket
        let socket = null;
        if (this.app.ws.user) {
          socket = this.app.ws.user[el.user_id];

        }
        //验证对方是否在线

        if (!socket) {
          console.log(123333, "343331")
          this.service.cache.setList("getmessage_" + el.user_id, message)

        } else {
          console.log(123333, "34333")
          //消息推送
          socket.send(JSON.stringify({
            msg: "ok",
            data: message
          }))
          //存到历史记录
          this.service.cache.setList(`chatlog_${el.user_id}_group_${currentid}`, message);
        }
      }
    });
  }
  async qrcode(){
    this.ctx.qrcode(JSON.stringify({
      id:this.ctx.params.id
    }));
  }
}

module.exports = GroupController;
